/*
 * Copyright 2011 Daniel Drown
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * nat64d.c - tun interface setup and main event loop
 */
#include "system_headers.h"
#include "ipv4.h"
#include "ipv6.h"
#include "nat64d.h"
#include "config.h"
#include "dhcpcd-files/netlink.h"
#include "logging.h"

#include <linux/capability.h>
#include <linux/prctl.h>
#include <private/android_filesystem_config.h>
#include <signal.h>

#define DEVICENAME "clat"

int forwarding_fd = -1;

/* function: set_forwarding
 * enables/disables ipv6 forwarding
 */
void set_forwarding(int fd, const char *setting) {
  /* we have to forward packets from the WAN to the tun interface */
  if(write(fd, setting, strlen(setting)) < 0) {
    logmsg(ANDROID_LOG_WARN,"set_forwarding failed: %s", strerror(errno));
  }
}

/* function: got_sigterm
 * signal handler: clean up and exit
 */
void got_sigterm(int signal) {
  if(forwarding_fd > 0) {
    set_forwarding(forwarding_fd, "0\n");
  }
  exit(0);
}

/* function: tun_open
 * tries to open the tunnel device
 */
int tun_open() {
  int fd;
  char *tundevpath;

  tundevpath = "/dev/tun";
  if(access(tundevpath, R_OK|W_OK) < 0) {
    tundevpath = "/dev/net/tun";
    if(access(tundevpath, R_OK|W_OK) < 0) {
      return -1;
    }
  }

  fd = open(tundevpath, O_RDWR);
  return fd;
}

/* function: tun_alloc
 * creates a tun interface and names it
 * dev - the name for the new tun device
 */
int tun_alloc(char *dev, int fd) {
  struct ifreq ifr;
  int err;

  memset(&ifr, 0, sizeof(ifr));

  ifr.ifr_flags = IFF_TUN; 
  if( *dev )
    strncpy(ifr.ifr_name, dev, IFNAMSIZ);

  if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
    close(fd);
    return err;
  }
  strcpy(dev, ifr.ifr_name);
  return fd;
}
/* function: configure_tun_ip
 * configures the ipv4 and ipv6 addresses on the tunnel interface
 * note: steals a /112 out of the (assumed routed to us) /64
 * device - device name to configure
 */
void configure_tun_ip(const char *device) {
  struct in6_addr local_nat64_prefix_6;
  struct in_addr local_nat64_prefix_4, local_nat64_prefix_4_brd, default_4;

  local_nat64_prefix_6 = config.ipv6_local_subnet;
  local_nat64_prefix_6.s6_addr32[3] |= htonl(0xff01);

  local_nat64_prefix_4 = config.ipv4_local_subnet;
  local_nat64_prefix_4.s_addr |= htonl(1);

  local_nat64_prefix_4_brd = local_nat64_prefix_4;
  local_nat64_prefix_4_brd.s_addr |= htonl(255);

  default_4.s_addr = 0x0;

  if(if_link(device, config.mtu, LINK_UP) < 0) {
    logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_link failed: %s",strerror(errno));
    exit(1);
  }

  if(if_address(device, AF_INET6, &local_nat64_prefix_6, 112, NULL, ADDRESS_ADD) < 0) {
    logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_address(6) failed: %s",strerror(errno));
    exit(1);
  }

  if(if_address(device, AF_INET, &local_nat64_prefix_4, 24, &local_nat64_prefix_4_brd, ADDRESS_ADD) < 0) {
    logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_address(4) failed: %s",strerror(errno));
    exit(1);
  }

  /* setup default ipv4 route */
  if(if_route(device, AF_INET, &default_4, 0, NULL, 1, config.ipv4mtu, ROUTE_REPLACE) < 0) {
    logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_route failed: %s",strerror(errno));
    exit(1);
  }
}

void drop_root() {
  gid_t groups[] = { AID_INET };
  setgroups(sizeof(groups)/sizeof(groups[0]), groups);

  prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);

  setgid(AID_CLATD);
  setuid(AID_CLATD);

  struct __user_cap_header_struct header;
  struct __user_cap_data_struct cap;
  header.version = _LINUX_CAPABILITY_VERSION;
  header.pid = 0;
  cap.inheritable = 
   cap.effective = cap.permitted = (1 << CAP_NET_ADMIN);
  capset(&header, &cap);
}

/* function: main
 * allocate and setup the tun device, then run the event loop
 */
int main() {
  int fd;
  char packet[PACKETLEN];
  char device[50] = DEVICENAME;
  ssize_t readlen;

  // open the tunnel device before dropping privs
  fd = tun_open();
  if(fd < 0) {
    logmsg(ANDROID_LOG_FATAL,"tun_open failed: %s",strerror(errno));
    exit(1);
  }

  // open the forwarding configuration before dropping privs
  forwarding_fd = open("/proc/sys/net/ipv6/conf/all/forwarding", O_RDWR);
  if(forwarding_fd < 0) {
    logmsg(ANDROID_LOG_FATAL,"open /proc/sys/net/ipv6/conf/all/forwarding failed: %s",strerror(errno));
    exit(1);
  }

  if(signal(SIGTERM, got_sigterm) == SIG_ERR) {
    logmsg(ANDROID_LOG_FATAL, "sigterm handler failed: %s", strerror(errno));
    exit(1);
  }

  // run under capabilities
  drop_root();

  if(!read_config("/data/local/etc/clatd.conf")) {
    logmsg(ANDROID_LOG_FATAL,"read_config failed");
    exit(1);
  }

  fd = tun_alloc(device, fd);
  if(fd < 0) {
    logmsg(ANDROID_LOG_FATAL,"tun_alloc failed: %s",strerror(errno));
    exit(1);
  }

  configure_tun_ip(device);

  set_forwarding(forwarding_fd,"1\n");

  while((readlen = read(fd,packet,PACKETLEN)) > 0) {
    uint16_t flags, proto;

    if(readlen < 4) {
      logmsg(ANDROID_LOG_WARN,"main/read short: got %ld bytes", readlen);
      continue;
    }
    
    flags = proto = 0;
    memcpy(&flags, packet, 2);
    memcpy(&proto, packet+2, 2);

    proto = ntohs(proto);
    flags = ntohs(flags);

    if(proto == ETH_P_IP) {
      ip_packet(fd,packet+4,readlen-4);
    } else if(proto == ETH_P_IPV6) {
      ipv6_packet(fd,packet+4,readlen-4);
    } else {
      logmsg(ANDROID_LOG_WARN,"main/unknown packet type = %x",proto);
    }

    memset(packet, 0, PACKETLEN);
  }

  set_forwarding(forwarding_fd,"0\n");

  return 0;
}
